﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using TechTree.Stalk.Roots.Common;

namespace TechTree.Stalk.Roots.Mailing
{
    public class MailingManager
    {
        private string _host;
        private int _port;
        private string _username;
        private string _password;

        public MailingManager(string host_, int port_, string username_, string password_)
        {
            _host = host_;
            _port = port_;
            _username = username_;
            _password = password_;
        }

        /// <summary>
        /// Transmits an email message without attachments
        /// </summary>
        /// <param name="recipient_">The Recipient.</param>
        /// <param name="sender_">The Sender.</param>
        /// <param name="subject_">The Subject.</param>
        /// <param name="body_">The Body.</param>
        /// <returns>The status of the message.</returns>
        public bool SendEmail(string recipient_, string sender_, string subject_, string body_)
        {
            try
            {
                // validates the e-mail.
                bool bValidaEmail = Tools.ValidateEmailAddress(sender_);

                // Se o email não é validao retorna uma mensagem
                if (bValidaEmail == false)
                    return false;

                // cria uma mensagem
                MailMessage mensagemEmail = new MailMessage(recipient_, sender_, subject_, body_);

                //----------------------------------------------------------------------------------------------------------------------------------
                //obtem os valores smtp do arquivo de configuração . Não vou usar estes valores estou apenas mostrando como obtê-los
                //Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(null);
                //MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
                //if (mailSettings != null)
                //{
                //    string host = mailSettings.Smtp.Network.Host;
                //    string password = mailSettings.Smtp.Network.Password;
                //    string username = mailSettings.Smtp.Network.UserName;
                //    int port = mailSettings.Smtp.Network.Port;
                //}
                //SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                //client.EnableSsl = true;
                //NetworkCredential cred = new NetworkCredential("macoratte@gmail.com", "hw8vup5e");
                //client.Credentials = cred;
                //---------------------------------------------------------------------------------------------------------------------------------------

                SmtpClient client = new SmtpClient(_host, _port);
                client.EnableSsl = true;
                NetworkCredential cred = new NetworkCredential(_username, _password);
                client.Credentials = cred;

                // inclui as credenciais
                client.UseDefaultCredentials = true;

                // envia a mensagem
                client.Send(mensagemEmail);

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// Transmits an email message with attachments.
        /// </summary>
        /// <param name="recipient_">The Recipient.</param>
        /// <param name="sender_">The Sender.</param>
        /// <param name="subject_">The Subject.</param>
        /// <param name="body_">The Body.</param>
        /// <param name="attachments_">An array of strings indicating the location of each attachment.</param>
        /// <returns>Status da mensagem</returns>
        public bool SendEmail(string recipient_, string sender_, string subject_, string body_, ArrayList attachments_)
        {
            try
            {
                // valida o email
                bool bValidaEmail = Tools.ValidateEmailAddress(recipient_);

                if (bValidaEmail == false)
                    return false;

                // Cria uma mensagem
                MailMessage mensagemEmail = new MailMessage(
                   sender_,
                   recipient_,
                   subject_,
                   body_);

                // The anexos arraylist should point to a file location where
                // the attachment resides - add the anexos to the message
                foreach (string attachment in attachments_)
                {
                    Attachment anexado = new Attachment(attachment, MediaTypeNames.Application.Octet);
                    mensagemEmail.Attachments.Add(anexado);
                }

                SmtpClient client = new SmtpClient(_host, _port);
                client.EnableSsl = true;
                NetworkCredential cred = new NetworkCredential(_username, _password);
                client.Credentials = cred;

                // Inclui as credenciais
                client.UseDefaultCredentials = true;

                // envia a mensagem
                client.Send(mensagemEmail);

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
